package com.lwsh.essearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwsh.essearch.dao.TSkuMapper;
import com.lwsh.essearch.document.EsSku;
import com.lwsh.essearch.model.TSku;
import com.lwsh.essearch.repository.EsSkuRepository;
import com.lwsh.essearch.service.EsSkuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * elasticsearch 搜索引擎 service实现
 * @author zhoudong
 * @version 0.1
 * @date 2018/12/13 15:33
 */
@Service
public class EsSkuServiceImpl extends BaseSearchServiceImpl<EsSku> implements EsSkuService {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Resource
    private EsSkuRepository esSkuRepository;
    @Resource
    private TSkuMapper tSkuMapper;

    @Override
    public int importAll() {
        int count = tSkuMapper.countByExample(null);
        int page = 1;
        int limit = 500;
        do {
            PageHelper.startPage(page, limit, "id asc");
            List<TSku> tSkuPageInfo = tSkuMapper.select(new TSku());
            PageInfo<TSku> pageList = new PageInfo<TSku>(tSkuPageInfo);

            List<EsSku> esSkus = pageList.getList().stream().map(e -> {
                EsSku esMallGoodsSpu = new EsSku();
                BeanUtils.copyProperties(e,esMallGoodsSpu);
                return esMallGoodsSpu;
            }).collect(Collectors.toList());
            esSkuRepository.saveAll(esSkus);
            page++;
            log.info("【保存索引】：{}",JSON.toJSONString(esSkus));

        } while (page * limit <= count);
        return count;
    }

    @Override
    public void save(EsSku... esSkus) {
        elasticsearchTemplate.putMapping(EsSku.class);
        if(esSkus.length > 0){
            /*Arrays.asList(productDocuments).parallelStream()
                    .map(productDocumentRepository::save)
                    .forEach(productDocument -> log.info("【保存数据】：{}", JSON.toJSONString(productDocument)));*/
            log.info("【保存索引】：{}",JSON.toJSONString(esSkuRepository.saveAll(Arrays.asList(esSkus))));
        }
    }

    @Override
    public void delete(Long id) {
        esSkuRepository.deleteById(id);
    }

    @Override
    public void deleteAll() {
        esSkuRepository.deleteAll();
    }

    @Override
    public EsSku getById(Long id) {
        return esSkuRepository.findById(id).get();
    }

    @Override
    public List<EsSku> getAll() {
        List<EsSku> list = new ArrayList<>();
        esSkuRepository.findAll().forEach(list::add);
        return list;
    }

}
